﻿#region Usings

using System.Collections.Generic;
using System.Windows;
using System.Windows.Shapes;
using Box2DX.Collision;
using Box2DX.Common;
using Box2DX.Dynamics;
using SilverBox.Physics;

#endregion

#if !SILVERLIGHT
using Tessellation;
#endif

namespace SilverBox.Helpers
{
    public static class ShapeHelper
    {
        public static void CreateShapesFromElement(Simulator simulator, Body body, BodyParameters bodyParameters,
                                                   Entity entity)
        {
            var shapeDefs = new List<ShapeDef>();

            if (entity.Shape is Ellipse)
            {
                var circleDef = new CircleDef();


                Vector2 worldRadius =
                    simulator.SimulatorContext.ScreenSizeToWorldSize(
                        new Size(entity.Shape.ActualWidth, entity.Shape.ActualHeight).Div(2));

                circleDef.Radius = worldRadius.Y;
                shapeDefs.Add(circleDef);
            }
            else if (entity.Shape is Rectangle)
            {
                var polygonDef = new PolygonDef();
                var rectangle = entity.Shape as Rectangle;

                var rect = new Rect(0, 0, rectangle.ActualWidth, rectangle.ActualHeight);
                Vector2 worldSize =
                    simulator.SimulatorContext.ScreenSizeToWorldSize(new Size(rect.Width, rect.Height).Div(2));
                polygonDef.SetAsBox(worldSize.X, worldSize.Y);
                shapeDefs.Add(polygonDef);
            }
            else if (entity.Shape is IShapeGeometry)
            {
                ShapeDef shapeDef = ((IShapeGeometry) entity.Shape).GetShapeDefinition(simulator.SimulatorContext);
                shapeDefs.Add(shapeDef);
            }
            else
            {
                Vector2 size = simulator.SimulatorContext.ScreenSizeToWorldSize(entity.ElementSize.Mul(0.5));
                var polygonDef = new PolygonDef();

                bodyParameters.SetParameters(polygonDef);

                polygonDef.SetAsBox(size.X, size.Y);
                shapeDefs.Add(polygonDef);
            }

            foreach (var shapeDef in shapeDefs)
            {
                bodyParameters.SetParameters(shapeDef);
                body.CreateShape(shapeDef);
            }
        }
    }
}